﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Text.RegularExpressions;
using InstantMessenger.MessengerServices;
using InstantMessenger.Interaction;

namespace InstantMessenger.UserControls
{
    /// <summary>
    /// User control register an account
    /// Created by: Dinh Quoc Vuong
    /// Created date: Oct 11th 2011
    /// </summary>
    [System.ComponentModel.ToolboxItem(true)]
    public partial class UCRegister : UCBase
    {
        #region Constructors
        /// <summary>
        /// Default constructor for design
        /// </summary>
        public UCRegister()
        {
            InitializeComponent();
            RegisterEvents();
        }

        /// <summary>
        /// Init with control changable
        /// </summary>
        /// <param name="controlChangable"></param>
        public UCRegister(IControlChangable controlChangable, MessengerServicesClient service)
            : base(controlChangable, service)
        {
            InitializeComponent();
            RegisterEvents();
        }

        /// <summary>
        /// Constructor set service
        /// </summary>
        /// <param name="currentService"></param>
        public UCRegister(MessengerServicesClient currentService)
            : base(currentService)
        {
            InitializeComponent();
            RegisterEvents();
        }
        #endregion

        private void btnSubmit_Click(object sender, EventArgs e)
        {
            bool isValid = CheckValid();
            if (isValid)
            {
                FileStream fs = null;
                bool isSuccess = false;
                try
                {
                    Users user = new Users();
                    user.UserName = txtUserName.Text;
                    user.Password = txtPassword.Text;
                    user.Email = txtEmail.Text;
                    user.SexID = cboSex.SelectedIndex;
                    user.FirstName = txtFirstName.Text;
                    user.LastName = txtLastName.Text;
                    user.Birthday = dtpBirthday.Value;

                    if (lblFileName.Tag != null)
                    {
                        fs = new FileStream(lblFileName.Tag.ToString(), FileMode.Open, FileAccess.Read);
                        _currentService.RegisterHasAvatar(user, fs);
                        isSuccess = true;
                    }
                    else
                    {
                        isSuccess = _currentService.Register(user);
                    }

                    if (isSuccess)
                    {
                        _conrolChangable.ChangeToLoginControl();
                    }
                }
                catch(Exception ex)
                {
                    isSuccess = false;
                    if (fs != null)
                    {
                        fs.Close();
                        fs.Dispose();
                    }
                }
            }
        }

        private void RegisterEvents()
        {
            txtUserName.LostFocus += new EventHandler(txtUserName_LostFocus);
            txtPassword.LostFocus += new EventHandler(txtPassword_LostFocus);
            txtRetypePassword.LostFocus += new EventHandler(txtRetypePassword_LostFocus);
            txtEmail.LostFocus += new EventHandler(txtEmail_LostFocus);
            txtFirstName.LostFocus += new EventHandler(txtFirstName_LostFocus);
            txtLastName.LostFocus += new EventHandler(txtLastName_LostFocus);
        }

        #region Lost focus events
        void txtLastName_LostFocus(object sender, EventArgs e)
        {
            ValidateLastName();
        }

        void txtFirstName_LostFocus(object sender, EventArgs e)
        {
            ValidateFirstName();
        }

        void txtRetypePassword_LostFocus(object sender, EventArgs e)
        {
            ValidateRetypePassword();
        }

        void txtPassword_LostFocus(object sender, EventArgs e)
        {
            ValidatePassword();
        }

        void txtEmail_LostFocus(object sender, EventArgs e)
        {
            ValidateEmail(false);
        }

        void txtUserName_LostFocus(object sender, EventArgs e)
        {
            ValidateUserName(false);
        }
        #endregion

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "Images|*.png;*.jpg";
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                string path = dlg.FileName;
                lblFileName.Text = Path.GetFileName(path);
                lblFileName.Tag = path;
            }
        }

        private void btnRemoveAvatar_Click(object sender, EventArgs e)
        {
            lblFileName.Text = "";
            lblFileName.Tag = null;
        }



        private void SetDefaultControlsValue()
        {
            //set default controls's value
            cboSex.SelectedIndex = 0;
        }

        private void UCRegister_Load(object sender, EventArgs e)
        {
            SetDefaultControlsValue();
        }

        #region Validate
        /// <summary>
        /// Validate data is valid
        /// </summary>
        /// <returns></returns>
        private bool CheckValid()
        {
            bool isValid = true;

            if (!ValidateUserName())
            {
                isValid = false;
            }

            if (!ValidatePassword())
            {
                isValid = false;
            }

            if (!ValidateRetypePassword())
            {
                isValid = false;
            }

            if (!ValidateEmail())
            {
                isValid = false;
            }

            if (!ValidateFirstName())
            {
                isValid = false;
            }

            if (!ValidateLastName())
            {
                isValid = false;
            }
            return isValid;
        }

        /// <summary>
        /// Validate first name
        /// </summary>
        /// <returns></returns>
        private bool ValidateFirstName()
        {
            bool isValid = true;
            if (string.IsNullOrWhiteSpace(txtFirstName.Text))
            {
                isValid = false;
                errProvider.SetError(txtFirstName, "Please enter your first name");
            }
            else
            {
                errProvider.SetError(txtFirstName, null);
            }
            return isValid;
        }

        /// <summary>
        /// Validate last name
        /// </summary>
        /// <returns></returns>
        private bool ValidateLastName()
        {
            bool isValid = true;
            if (string.IsNullOrWhiteSpace(txtLastName.Text))
            {
                isValid = false;
                errProvider.SetError(txtLastName, "Please enter your last name");
            }
            else
            {
                errProvider.SetError(txtLastName, null);
            }
            return isValid;
        }

        /// <summary>
        /// Validate email
        /// </summary>
        /// <param name="isCheckExist">Is check exist</param>
        /// <returns></returns>
        private bool ValidateEmail(bool isCheckExist = true)
        {
            bool isValid = true;
            if (string.IsNullOrWhiteSpace(txtEmail.Text))
            {
                isValid = false;
                errProvider.SetError(txtEmail, "Please enter your email");
            }
            else
            {
                string regExpEmail = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
                   @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
                   @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
                if (!Regex.IsMatch(txtEmail.Text, regExpEmail))
                {
                    isValid = false;
                    errProvider.SetError(txtEmail, "Your email is not valid");
                }
                else
                {
                    if (isCheckExist && _currentService.CheckEmailIsExist(txtEmail.Text))
                    {
                        errProvider.SetError(txtEmail, "This email was exist. Please choose another one");
                    }
                    else
                    {
                        errProvider.SetError(txtEmail, null);
                    }
                }
            }
            return isValid;
        }

        /// <summary>
        /// Validate retype password
        /// </summary>
        /// <returns></returns>
        private bool ValidateRetypePassword()
        {
            bool isValid = true;
            if (txtPassword.Text.Trim() != txtRetypePassword.Text.Trim())
            {
                isValid = false;
                errProvider.SetError(txtRetypePassword, "Retype password does not match");
            }
            else
            {
                errProvider.SetError(txtRetypePassword, null);
            }
            return isValid;
        }

        /// <summary>
        /// Validate password
        /// </summary>
        /// <returns></returns>
        private bool ValidatePassword()
        {
            bool isValid = true;
            if (txtPassword.Text.Trim().Length < 6)
            {
                isValid = false;
                errProvider.SetError(txtPassword, "Password length must greater or equals 6 characters");
            }
            else
            {
                errProvider.SetError(txtPassword, null);
            }
            return isValid;
        }

        /// <summary>
        /// Validate user name
        /// </summary>
        /// <param name="isCheckExist">Is check exist</param>
        /// <returns></returns>
        private bool ValidateUserName(bool isCheckExist = true)
        {
            bool isValid = true;
            if (string.IsNullOrWhiteSpace(txtUserName.Text))
            {
                isValid = false;
                errProvider.SetError(txtUserName, "Please enter your user name");
            }
            else
            {

                if (isCheckExist && _currentService.CheckUserNameIsExist(txtUserName.Text))
                {
                    errProvider.SetError(txtUserName, "This user name was exist. Please choose another one");
                }
                else
                {
                    errProvider.SetError(txtUserName, null);
                }
            }
            return isValid;
        }
        #endregion

        #region Navigations
        private void lnkLogin_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            _conrolChangable.ChangeToLoginControl();
        }

        private void lnkForgotPassword_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            _conrolChangable.ChangeToForgotPassword();
        }
        #endregion

        private void btnCheckUsername_Click(object sender, EventArgs e)
        {
            ValidateUserName();
        }

        private void btnCheckEmail_Click(object sender, EventArgs e)
        {
            ValidateEmail();
        }

    }
}
